home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-gdata / gdata / __init__.py next >
Encoding:
Python Source  |  2009-02-11  |  29.2 KB  |  835 lines

  1. #
  2. # Copyright (C) 2006 Google Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. #      http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15.  
  16.  
  17. """Contains classes representing Google Data elements.
  18.  
  19.   Extends Atom classes to add Google Data specific elements.
  20. """
  21.  
  22.  
  23. __author__ = 'api.jscudder (Jeffrey Scudder)'
  24.  
  25. import os
  26. import atom
  27. try:
  28.   from xml.etree import cElementTree as ElementTree
  29. except ImportError:
  30.   try:
  31.     import cElementTree as ElementTree
  32.   except ImportError:
  33.     try:
  34.       from xml.etree import ElementTree
  35.     except ImportError:
  36.       from elementtree import ElementTree
  37.  
  38.  
  39. # XML namespaces which are often used in GData entities.
  40. GDATA_NAMESPACE = 'http://schemas.google.com/g/2005'
  41. GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s'
  42. OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/'
  43. OPENSEARCH_TEMPLATE = '{http://a9.com/-/spec/opensearchrss/1.0/}%s'
  44. BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch'
  45. GACL_NAMESPACE = 'http://schemas.google.com/acl/2007'
  46. GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s'
  47.  
  48.  
  49. # Labels used in batch request entries to specify the desired CRUD operation.
  50. BATCH_INSERT = 'insert'
  51. BATCH_UPDATE = 'update'
  52. BATCH_DELETE = 'delete'
  53. BATCH_QUERY = 'query'
  54.  
  55. class Error(Exception):
  56.   pass
  57.  
  58.  
  59. class MissingRequiredParameters(Error):
  60.   pass
  61.  
  62.  
  63. class MediaSource(object):
  64.   """GData Entries can refer to media sources, so this class provides a
  65.   place to store references to these objects along with some metadata.
  66.   """
  67.   
  68.   def __init__(self, file_handle=None, content_type=None, content_length=None,
  69.       file_path=None, file_name=None):
  70.     """Creates an object of type MediaSource.
  71.  
  72.     Args:
  73.       file_handle: A file handle pointing to the file to be encapsulated in the
  74.                    MediaSource
  75.       content_type: string The MIME type of the file. Required if a file_handle
  76.                     is given.
  77.       content_length: int The size of the file. Required if a file_handle is
  78.                       given.
  79.       file_path: string (optional) A full path name to the file. Used in
  80.                     place of a file_handle.
  81.       file_name: string The name of the file without any path information.
  82.                  Required if a file_handle is given.
  83.     """
  84.     self.file_handle = file_handle
  85.     self.content_type = content_type
  86.     self.content_length = content_length
  87.     self.file_name = file_name
  88.  
  89.     if (file_handle is None and content_type is not None and
  90.         file_path is not None):
  91.       self.setFile(file_path, content_type)
  92.  
  93.   def setFile(self, file_name, content_type):
  94.     """A helper function which can create a file handle from a given filename
  95.     and set the content type and length all at once.
  96.  
  97.     Args:
  98.       file_name: string The path and file name to the file containing the media
  99.       content_type: string A MIME type representing the type of the media
  100.     """
  101.  
  102.     self.file_handle = open(file_name, 'rb')
  103.     self.content_type = content_type
  104.     self.content_length = os.path.getsize(file_name)
  105.     self.file_name = os.path.basename(file_name)
  106.   
  107.  
  108. class LinkFinder(atom.LinkFinder):
  109.   """An "interface" providing methods to find link elements
  110.  
  111.   GData Entry elements often contain multiple links which differ in the rel
  112.   attribute or content type. Often, developers are interested in a specific
  113.   type of link so this class provides methods to find specific classes of
  114.   links.
  115.  
  116.   This class is used as a mixin in GData entries.
  117.   """
  118.  
  119.   def GetSelfLink(self):
  120.     """Find the first link with rel set to 'self'
  121.  
  122.     Returns:
  123.       An atom.Link or none if none of the links had rel equal to 'self'
  124.     """
  125.  
  126.     for a_link in self.link:
  127.       if a_link.rel == 'self':
  128.         return a_link
  129.     return None
  130.  
  131.   def GetEditLink(self):
  132.     for a_link in self.link:
  133.       if a_link.rel == 'edit':
  134.         return a_link
  135.     return None
  136.     
  137.   def GetEditMediaLink(self):
  138.     """The Picasa API mistakenly returns media-edit rather than edit-media, but
  139.     this may change soon.
  140.     """
  141.     for a_link in self.link:
  142.       if a_link.rel == 'edit-media':
  143.         return a_link
  144.       if a_link.rel == 'media-edit':
  145.         return a_link
  146.     return None
  147.  
  148.   def GetHtmlLink(self):
  149.     """Find the first link with rel of alternate and type of text/html
  150.  
  151.     Returns:
  152.       An atom.Link or None if no links matched
  153.     """
  154.     for a_link in self.link:
  155.       if a_link.rel == 'alternate' and a_link.type == 'text/html':
  156.         return a_link
  157.     return None
  158.  
  159.   def GetPostLink(self):
  160.     """Get a link containing the POST target URL.
  161.     
  162.     The POST target URL is used to insert new entries.
  163.  
  164.     Returns:
  165.       A link object with a rel matching the POST type.
  166.     """
  167.     for a_link in self.link:
  168.       if a_link.rel == 'http://schemas.google.com/g/2005#post':
  169.         return a_link
  170.     return None
  171.  
  172.   def GetAclLink(self):
  173.     for a_link in self.link:
  174.       if a_link.rel == 'http://schemas.google.com/acl/2007#accessControlList':
  175.         return a_link
  176.     return None
  177.  
  178.   def GetFeedLink(self):
  179.     for a_link in self.link:
  180.       if a_link.rel == 'http://schemas.google.com/g/2005#feed':
  181.         return a_link
  182.     return None
  183.  
  184.   def GetNextLink(self):
  185.     for a_link in self.link:
  186.       if a_link.rel == 'next':
  187.         return a_link
  188.     return None
  189.  
  190.   def GetPrevLink(self):
  191.     for a_link in self.link:
  192.       if a_link.rel == 'previous':
  193.         return a_link
  194.     return None
  195.  
  196.  
  197. class TotalResults(atom.AtomBase):
  198.   """opensearch:TotalResults for a GData feed"""
  199.   
  200.   _tag = 'totalResults'
  201.   _namespace = OPENSEARCH_NAMESPACE
  202.   _children = atom.AtomBase._children.copy()
  203.   _attributes = atom.AtomBase._attributes.copy()
  204.  
  205.   def __init__(self, extension_elements=None,
  206.      extension_attributes=None, text=None):
  207.     self.text = text
  208.     self.extension_elements = extension_elements or []
  209.     self.extension_attributes = extension_attributes or {}
  210.  
  211.  
  212. def TotalResultsFromString(xml_string):
  213.   return atom.CreateClassFromXMLString(TotalResults, xml_string)
  214.  
  215.   
  216. class StartIndex(atom.AtomBase):
  217.   """The opensearch:startIndex element in GData feed"""
  218.  
  219.   _tag = 'startIndex'
  220.   _namespace = OPENSEARCH_NAMESPACE
  221.   _children = atom.AtomBase._children.copy()
  222.   _attributes = atom.AtomBase._attributes.copy()
  223.  
  224.   def __init__(self, extension_elements=None, 
  225.       extension_attributes=None, text=None):
  226.     self.text = text
  227.     self.extension_elements = extension_elements or []
  228.     self.extension_attributes = extension_attributes or {}
  229.  
  230.  
  231. def StartIndexFromString(xml_string):
  232.   return atom.CreateClassFromXMLString(StartIndex, xml_string)
  233.  
  234.  
  235. class ItemsPerPage(atom.AtomBase):
  236.   """The opensearch:itemsPerPage element in GData feed"""
  237.  
  238.   _tag = 'itemsPerPage'
  239.   _namespace = OPENSEARCH_NAMESPACE
  240.   _children = atom.AtomBase._children.copy()
  241.   _attributes = atom.AtomBase._attributes.copy()
  242.  
  243.   def __init__(self, extension_elements=None,
  244.       extension_attributes=None, text=None):
  245.     self.text = text
  246.     self.extension_elements = extension_elements or []
  247.     self.extension_attributes = extension_attributes or {}
  248.  
  249.  
  250. def ItemsPerPageFromString(xml_string):
  251.   return atom.CreateClassFromXMLString(ItemsPerPage, xml_string)
  252.  
  253.  
  254. class ExtendedProperty(atom.AtomBase):
  255.   """The Google Data extendedProperty element.
  256.   
  257.   Used to store arbitrary key-value information specific to your
  258.   application. The value can either be a text string stored as an XML 
  259.   attribute (.value), or an XML node (XmlBlob) as a child element.
  260.  
  261.   This element is used in the Google Calendar data API and the Google
  262.   Contacts data API.
  263.   """
  264.  
  265.   _tag = 'extendedProperty'
  266.   _namespace = GDATA_NAMESPACE
  267.   _children = atom.AtomBase._children.copy()
  268.   _attributes = atom.AtomBase._attributes.copy()
  269.   _attributes['name'] = 'name'
  270.   _attributes['value'] = 'value'
  271.  
  272.   def __init__(self, name=None, value=None, extension_elements=None,
  273.       extension_attributes=None, text=None):
  274.     self.name = name
  275.     self.value = value
  276.     self.text = text
  277.     self.extension_elements = extension_elements or []
  278.     self.extension_attributes = extension_attributes or {}
  279.  
  280.   def GetXmlBlobExtensionElement(self):
  281.     """Returns the XML blob as an atom.ExtensionElement.
  282.     
  283.     Returns:
  284.       An atom.ExtensionElement representing the blob's XML, or None if no
  285.       blob was set.
  286.     """
  287.     if len(self.extension_elements) < 1:
  288.       return None
  289.     else:
  290.       return self.extension_elements[0]
  291.  
  292.   def GetXmlBlobString(self):
  293.     """Returns the XML blob as a string.
  294.  
  295.     Returns:
  296.       A string containing the blob's XML, or None if no blob was set.
  297.     """
  298.     blob = self.GetXmlBlobExtensionElement()
  299.     if blob:
  300.       return blob.ToString()
  301.     return None
  302.  
  303.   def SetXmlBlob(self, blob):
  304.     """Sets the contents of the extendedProperty to XML as a child node.
  305.  
  306.     Since the extendedProperty is only allowed one child element as an XML
  307.     blob, setting the XML blob will erase any preexisting extension elements
  308.     in this object.
  309.  
  310.     Args:
  311.       blob: str, ElementTree Element or atom.ExtensionElement representing
  312.             the XML blob stored in the extendedProperty.
  313.     """
  314.     # Erase any existing extension_elements, clears the child nodes from the
  315.     # extendedProperty.
  316.     self.extension_elements = []
  317.     if isinstance(blob, atom.ExtensionElement):
  318.       self.extension_elements.append(blob)
  319.     elif ElementTree.iselement(blob):
  320.       self.extension_elements.append(atom._ExtensionElementFromElementTree(
  321.           blob))
  322.     else:
  323.       self.extension_elements.append(atom.ExtensionElementFromString(blob))
  324.  
  325.  
  326. def ExtendedPropertyFromString(xml_string):
  327.   return atom.CreateClassFromXMLString(ExtendedProperty, xml_string)
  328.  
  329.  
  330. class GDataEntry(atom.Entry, LinkFinder):
  331.   """Extends Atom Entry to provide data processing"""
  332.  
  333.   _tag = atom.Entry._tag
  334.   _namespace = atom.Entry._namespace
  335.   _children = atom.Entry._children.copy()
  336.   _attributes = atom.Entry._attributes.copy()
  337.  
  338.   def __GetId(self):
  339.     return self.__id
  340.  
  341.   # This method was created to strip the unwanted whitespace from the id's 
  342.   # text node.
  343.   def __SetId(self, id):
  344.     self.__id = id
  345.     if id is not None and id.text is not None:
  346.       self.__id.text = id.text.strip()
  347.  
  348.   id = property(__GetId, __SetId)
  349.   
  350.   def IsMedia(self):
  351.     """Determines whether or not an entry is a GData Media entry.
  352.     """
  353.     if (self.GetEditMediaLink()):
  354.       return True
  355.     else:
  356.       return False
  357.   
  358.   def GetMediaURL(self):
  359.     """Returns the URL to the media content, if the entry is a media entry.
  360.     Otherwise returns None.
  361.     """
  362.     if not self.IsMedia():
  363.       return None
  364.     else:
  365.       return self.content.src
  366.  
  367.  
  368. def GDataEntryFromString(xml_string):
  369.   """Creates a new GDataEntry instance given a string of XML."""
  370.   return atom.CreateClassFromXMLString(GDataEntry, xml_string)
  371.  
  372.  
  373. class GDataFeed(atom.Feed, LinkFinder):
  374.   """A Feed from a GData service"""
  375.  
  376.   _tag = 'feed'
  377.   _namespace = atom.ATOM_NAMESPACE
  378.   _children = atom.Feed._children.copy()
  379.   _attributes = atom.Feed._attributes.copy()
  380.   _children['{%s}totalResults' % OPENSEARCH_NAMESPACE] = ('total_results', 
  381.                                                           TotalResults)
  382.   _children['{%s}startIndex' % OPENSEARCH_NAMESPACE] = ('start_index', 
  383.                                                         StartIndex)
  384.   _children['{%s}itemsPerPage' % OPENSEARCH_NAMESPACE] = ('items_per_page',
  385.                                                           ItemsPerPage)
  386.                # Add a conversion rule for atom:entry to make it into a GData
  387.                # Entry.
  388.   _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GDataEntry])
  389.  
  390.   def __GetId(self):
  391.     return self.__id
  392.  
  393.   def __SetId(self, id):
  394.     self.__id = id
  395.     if id is not None and id.text is not None:
  396.       self.__id.text = id.text.strip()
  397.  
  398.   id = property(__GetId, __SetId)
  399.  
  400.   def __GetGenerator(self):
  401.     return self.__generator
  402.  
  403.   def __SetGenerator(self, generator):
  404.     self.__generator = generator
  405.     if generator is not None:
  406.       self.__generator.text = generator.text.strip()
  407.  
  408.   generator = property(__GetGenerator, __SetGenerator)
  409.  
  410.   def __init__(self, author=None, category=None, contributor=None,
  411.       generator=None, icon=None, atom_id=None, link=None, logo=None, 
  412.       rights=None, subtitle=None, title=None, updated=None, entry=None, 
  413.       total_results=None, start_index=None, items_per_page=None,
  414.       extension_elements=None, extension_attributes=None, text=None):
  415.     """Constructor for Source
  416.     
  417.     Args:
  418.       author: list (optional) A list of Author instances which belong to this
  419.           class.
  420.       category: list (optional) A list of Category instances
  421.       contributor: list (optional) A list on Contributor instances
  422.       generator: Generator (optional) 
  423.       icon: Icon (optional) 
  424.       id: Id (optional) The entry's Id element
  425.       link: list (optional) A list of Link instances
  426.       logo: Logo (optional) 
  427.       rights: Rights (optional) The entry's Rights element
  428.       subtitle: Subtitle (optional) The entry's subtitle element
  429.       title: Title (optional) the entry's title element
  430.       updated: Updated (optional) the entry's updated element
  431.       entry: list (optional) A list of the Entry instances contained in the 
  432.           feed.
  433.       text: String (optional) The text contents of the element. This is the 
  434.           contents of the Entry's XML text node. 
  435.           (Example: <foo>This is the text</foo>)
  436.       extension_elements: list (optional) A list of ExtensionElement instances
  437.           which are children of this element.
  438.       extension_attributes: dict (optional) A dictionary of strings which are 
  439.           the values for additional XML attributes of this element.
  440.     """
  441.  
  442.     self.author = author or []
  443.     self.category = category or []
  444.     self.contributor = contributor or []
  445.     self.generator = generator
  446.     self.icon = icon
  447.     self.id = atom_id
  448.     self.link = link or []
  449.     self.logo = logo
  450.     self.rights = rights
  451.     self.subtitle = subtitle
  452.     self.title = title
  453.     self.updated = updated
  454.     self.entry = entry or []
  455.     self.total_results = total_results
  456.     self.start_index = start_index
  457.     self.items_per_page = items_per_page
  458.     self.text = text
  459.     self.extension_elements = extension_elements or []
  460.     self.extension_attributes = extension_attributes or {}
  461.  
  462.  
  463. def GDataFeedFromString(xml_string):
  464.   return atom.CreateClassFromXMLString(GDataFeed, xml_string)
  465.  
  466.  
  467. class BatchId(atom.AtomBase):
  468.   _tag = 'id'
  469.   _namespace = BATCH_NAMESPACE
  470.   _children = atom.AtomBase._children.copy()
  471.   _attributes = atom.AtomBase._attributes.copy()
  472.  
  473.  
  474. def BatchIdFromString(xml_string):
  475.   return atom.CreateClassFromXMLString(BatchId, xml_string)
  476.  
  477.  
  478. class BatchOperation(atom.AtomBase):
  479.   _tag = 'operation'
  480.   _namespace = BATCH_NAMESPACE
  481.   _children = atom.AtomBase._children.copy()
  482.   _attributes = atom.AtomBase._attributes.copy()
  483.   _attributes['type'] = 'type'
  484.  
  485.   def __init__(self, op_type=None, extension_elements=None, 
  486.                extension_attributes=None,
  487.                text=None):
  488.     self.type = op_type
  489.     atom.AtomBase.__init__(self, 
  490.                            extension_elements=extension_elements, 
  491.                            extension_attributes=extension_attributes, 
  492.                            text=text)
  493.  
  494.  
  495. def BatchOperationFromString(xml_string):
  496.   return atom.CreateClassFromXMLString(BatchOperation, xml_string)
  497.  
  498.  
  499. class BatchStatus(atom.AtomBase):
  500.   """The batch:status element present in a batch response entry.
  501.   
  502.   A status element contains the code (HTTP response code) and 
  503.   reason as elements. In a single request these fields would
  504.   be part of the HTTP response, but in a batch request each
  505.   Entry operation has a corresponding Entry in the response
  506.   feed which includes status information.
  507.  
  508.   See http://code.google.com/apis/gdata/batch.html#Handling_Errors
  509.   """
  510.  
  511.   _tag = 'status'
  512.   _namespace = BATCH_NAMESPACE
  513.   _children = atom.AtomBase._children.copy()
  514.   _attributes = atom.AtomBase._attributes.copy()
  515.   _attributes['code'] = 'code'
  516.   _attributes['reason'] = 'reason'
  517.   _attributes['content-type'] = 'content_type'
  518.  
  519.   def __init__(self, code=None, reason=None, content_type=None, 
  520.                extension_elements=None, extension_attributes=None, text=None):
  521.     self.code = code
  522.     self.reason = reason
  523.     self.content_type = content_type
  524.     atom.AtomBase.__init__(self, extension_elements=extension_elements,
  525.                            extension_attributes=extension_attributes, 
  526.                            text=text)
  527.  
  528.  
  529. def BatchStatusFromString(xml_string):
  530.   return atom.CreateClassFromXMLString(BatchStatus, xml_string)
  531.  
  532.  
  533. class BatchEntry(GDataEntry):
  534.   """An atom:entry for use in batch requests.
  535.  
  536.   The BatchEntry contains additional members to specify the operation to be
  537.   performed on this entry and a batch ID so that the server can reference
  538.   individual operations in the response feed. For more information, see:
  539.   http://code.google.com/apis/gdata/batch.html
  540.   """
  541.  
  542.   _tag = GDataEntry._tag
  543.   _namespace = GDataEntry._namespace
  544.   _children = GDataEntry._children.copy()
  545.   _children['{%s}operation' % BATCH_NAMESPACE] = ('batch_operation', BatchOperation) 
  546.   _children['{%s}id' % BATCH_NAMESPACE] = ('batch_id', BatchId)
  547.   _children['{%s}status' % BATCH_NAMESPACE] = ('batch_status', BatchStatus)
  548.   _attributes = GDataEntry._attributes.copy()
  549.  
  550.   def __init__(self, author=None, category=None, content=None,
  551.       contributor=None, atom_id=None, link=None, published=None, rights=None,
  552.       source=None, summary=None, control=None, title=None, updated=None,
  553.       batch_operation=None, batch_id=None, batch_status=None,
  554.       extension_elements=None, extension_attributes=None, text=None):
  555.     self.batch_operation = batch_operation
  556.     self.batch_id = batch_id
  557.     self.batch_status = batch_status
  558.     GDataEntry.__init__(self, author=author, category=category, 
  559.         content=content, contributor=contributor, atom_id=atom_id, link=link, 
  560.         published=published, rights=rights, source=source, summary=summary, 
  561.         control=control, title=title, updated=updated, 
  562.         extension_elements=extension_elements, 
  563.         extension_attributes=extension_attributes, text=text)
  564.  
  565.  
  566. def BatchEntryFromString(xml_string):
  567.   return atom.CreateClassFromXMLString(BatchEntry, xml_string)
  568.  
  569.  
  570. class BatchInterrupted(atom.AtomBase):
  571.   """The batch:interrupted element sent if batch request was interrupted.
  572.   
  573.   Only appears in a feed if some of the batch entries could not be processed.
  574.   See: http://code.google.com/apis/gdata/batch.html#Handling_Errors
  575.   """
  576.  
  577.   _tag = 'interrupted'
  578.   _namespace = BATCH_NAMESPACE
  579.   _children = atom.AtomBase._children.copy()
  580.   _attributes = atom.AtomBase._attributes.copy()
  581.   _attributes['reason'] = 'reason'
  582.   _attributes['success'] = 'success'
  583.   _attributes['failures'] = 'failures'
  584.   _attributes['parsed'] = 'parsed'
  585.  
  586.   def __init__(self, reason=None, success=None, failures=None, parsed=None, 
  587.                extension_elements=None, extension_attributes=None, text=None):
  588.     self.reason = reason
  589.     self.success = success
  590.     self.failures = failures
  591.     self.parsed = parsed
  592.     atom.AtomBase.__init__(self, extension_elements=extension_elements,
  593.                            extension_attributes=extension_attributes, 
  594.                            text=text)
  595.  
  596.  
  597. def BatchInterruptedFromString(xml_string):
  598.   return atom.CreateClassFromXMLString(BatchInterrupted, xml_string)
  599.  
  600.  
  601. class BatchFeed(GDataFeed):
  602.   """A feed containing a list of batch request entries."""
  603.  
  604.   _tag = GDataFeed._tag
  605.   _namespace = GDataFeed._namespace
  606.   _children = GDataFeed._children.copy()
  607.   _attributes = GDataFeed._attributes.copy()
  608.   _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BatchEntry])
  609.   _children['{%s}interrupted' % BATCH_NAMESPACE] = ('interrupted', BatchInterrupted)
  610.  
  611.   def __init__(self, author=None, category=None, contributor=None,
  612.       generator=None, icon=None, atom_id=None, link=None, logo=None,
  613.       rights=None, subtitle=None, title=None, updated=None, entry=None,
  614.       total_results=None, start_index=None, items_per_page=None,
  615.       interrupted=None,
  616.       extension_elements=None, extension_attributes=None, text=None):
  617.     self.interrupted = interrupted
  618.     GDataFeed.__init__(self, author=author, category=category, 
  619.                        contributor=contributor, generator=generator, 
  620.                        icon=icon, atom_id=atom_id, link=link, 
  621.                        logo=logo, rights=rights, subtitle=subtitle,
  622.                        title=title, updated=updated, entry=entry,
  623.                        total_results=total_results, start_index=start_index,
  624.                        items_per_page=items_per_page,
  625.                        extension_elements=extension_elements, 
  626.                        extension_attributes=extension_attributes,
  627.                        text=text)
  628.  
  629.   def AddBatchEntry(self, entry=None, id_url_string=None, 
  630.                      batch_id_string=None, operation_string=None):
  631.     """Logic for populating members of a BatchEntry and adding to the feed.
  632.  
  633.     
  634.     If the entry is not a BatchEntry, it is converted to a BatchEntry so
  635.     that the batch specific members will be present. 
  636.  
  637.     The id_url_string can be used in place of an entry if the batch operation
  638.     applies to a URL. For example query and delete operations require just
  639.     the URL of an entry, no body is sent in the HTTP request. If an
  640.     id_url_string is sent instead of an entry, a BatchEntry is created and
  641.     added to the feed.
  642.  
  643.     This method also assigns the desired batch id to the entry so that it 
  644.     can be referenced in the server's response. If the batch_id_string is
  645.     None, this method will assign a batch_id to be the index at which this
  646.     entry will be in the feed's entry list.
  647.     
  648.     Args:
  649.       entry: BatchEntry, atom.Entry, or another Entry flavor (optional) The
  650.           entry which will be sent to the server as part of the batch request.
  651.           The item must have a valid atom id so that the server knows which 
  652.           entry this request references.
  653.       id_url_string: str (optional) The URL of the entry to be acted on. You
  654.           can find this URL in the text member of the atom id for an entry.
  655.           If an entry is not sent, this id will be used to construct a new
  656.           BatchEntry which will be added to the request feed.
  657.       batch_id_string: str (optional) The batch ID to be used to reference
  658.           this batch operation in the results feed. If this parameter is None,
  659.           the current length of the feed's entry array will be used as a
  660.           count. Note that batch_ids should either always be specified or
  661.           never, mixing could potentially result in duplicate batch ids.
  662.       operation_string: str (optional) The desired batch operation which will
  663.           set the batch_operation.type member of the entry. Options are
  664.           'insert', 'update', 'delete', and 'query'
  665.     
  666.     Raises:
  667.       MissingRequiredParameters: Raised if neither an id_ url_string nor an
  668.           entry are provided in the request.
  669.  
  670.     Returns:
  671.       The added entry.
  672.     """
  673.     if entry is None and id_url_string is None:
  674.       raise MissingRequiredParameters('supply either an entry or URL string')
  675.     if entry is None and id_url_string is not None:
  676.       entry = BatchEntry(atom_id=atom.Id(text=id_url_string))
  677.     # TODO: handle cases in which the entry lacks batch_... members.
  678.     #if not isinstance(entry, BatchEntry):
  679.       # Convert the entry to a batch entry.
  680.     if batch_id_string is not None:
  681.       entry.batch_id = BatchId(text=batch_id_string)
  682.     elif entry.batch_id is None or entry.batch_id.text is None:
  683.       entry.batch_id = BatchId(text=str(len(self.entry)))
  684.     if operation_string is not None:
  685.       entry.batch_operation = BatchOperation(op_type=operation_string)
  686.     self.entry.append(entry)
  687.     return entry
  688.  
  689.   def AddInsert(self, entry, batch_id_string=None):
  690.     """Add an insert request to the operations in this batch request feed.
  691.  
  692.     If the entry doesn't yet have an operation or a batch id, these will
  693.     be set to the insert operation and a batch_id specified as a parameter.
  694.  
  695.     Args:
  696.       entry: BatchEntry The entry which will be sent in the batch feed as an
  697.           insert request.
  698.       batch_id_string: str (optional) The batch ID to be used to reference
  699.           this batch operation in the results feed. If this parameter is None,
  700.           the current length of the feed's entry array will be used as a
  701.           count. Note that batch_ids should either always be specified or
  702.           never, mixing could potentially result in duplicate batch ids.
  703.     """
  704.     entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
  705.                                operation_string=BATCH_INSERT)
  706.   
  707.   def AddUpdate(self, entry, batch_id_string=None):
  708.     """Add an update request to the list of batch operations in this feed.
  709.  
  710.     Sets the operation type of the entry to insert if it is not already set
  711.     and assigns the desired batch id to the entry so that it can be 
  712.     referenced in the server's response.
  713.  
  714.     Args:
  715.       entry: BatchEntry The entry which will be sent to the server as an
  716.           update (HTTP PUT) request. The item must have a valid atom id
  717.           so that the server knows which entry to replace.
  718.       batch_id_string: str (optional) The batch ID to be used to reference
  719.           this batch operation in the results feed. If this parameter is None,
  720.           the current length of the feed's entry array will be used as a
  721.           count. See also comments for AddInsert.
  722.     """
  723.     entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
  724.                                operation_string=BATCH_UPDATE)
  725.  
  726.   def AddDelete(self, url_string=None, entry=None, batch_id_string=None):
  727.     """Adds a delete request to the batch request feed.
  728.  
  729.     This method takes either the url_string which is the atom id of the item
  730.     to be deleted, or the entry itself. The atom id of the entry must be 
  731.     present so that the server knows which entry should be deleted.
  732.  
  733.     Args:
  734.       url_string: str (optional) The URL of the entry to be deleted. You can
  735.          find this URL in the text member of the atom id for an entry. 
  736.       entry: BatchEntry (optional) The entry to be deleted.
  737.       batch_id_string: str (optional)
  738.  
  739.     Raises:
  740.       MissingRequiredParameters: Raised if neither a url_string nor an entry 
  741.           are provided in the request. 
  742.     """
  743.     entry = self.AddBatchEntry(entry=entry, id_url_string=url_string, 
  744.                                batch_id_string=batch_id_string, 
  745.                                operation_string=BATCH_DELETE)
  746.  
  747.   def AddQuery(self, url_string=None, entry=None, batch_id_string=None):
  748.     """Adds a query request to the batch request feed.
  749.  
  750.     This method takes either the url_string which is the query URL 
  751.     whose results will be added to the result feed. The query URL will
  752.     be encapsulated in a BatchEntry, and you may pass in the BatchEntry
  753.     with a query URL instead of sending a url_string.
  754.  
  755.     Args:
  756.       url_string: str (optional)
  757.       entry: BatchEntry (optional)
  758.       batch_id_string: str (optional)
  759.  
  760.     Raises:
  761.       MissingRequiredParameters
  762.     """
  763.     entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
  764.                                batch_id_string=batch_id_string,
  765.                                operation_string=BATCH_QUERY)
  766.  
  767.   def GetBatchLink(self):
  768.     for link in self.link:
  769.       if link.rel == 'http://schemas.google.com/g/2005#batch':
  770.         return link
  771.     return None
  772.  
  773.  
  774. def BatchFeedFromString(xml_string):
  775.   return atom.CreateClassFromXMLString(BatchFeed, xml_string)
  776.   
  777.  
  778. class EntryLink(atom.AtomBase):
  779.   """The gd:entryLink element"""
  780.  
  781.   _tag = 'entryLink'
  782.   _namespace = GDATA_NAMESPACE
  783.   _children = atom.AtomBase._children.copy()
  784.   _attributes = atom.AtomBase._attributes.copy()
  785.   # The entry used to be an atom.Entry, now it is a GDataEntry.
  786.   _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', GDataEntry)
  787.   _attributes['rel'] = 'rel'
  788.   _attributes['readOnly'] = 'read_only'
  789.   _attributes['href'] = 'href'
  790.   
  791.   def __init__(self, href=None, read_only=None, rel=None,
  792.       entry=None, extension_elements=None, 
  793.       extension_attributes=None, text=None):
  794.     self.href = href
  795.     self.read_only = read_only
  796.     self.rel = rel
  797.     self.entry = entry
  798.     self.text = text
  799.     self.extension_elements = extension_elements or []
  800.     self.extension_attributes = extension_attributes or {}
  801.     
  802.  
  803. def EntryLinkFromString(xml_string):
  804.   return atom.CreateClassFromXMLString(EntryLink, xml_string)
  805.  
  806.  
  807. class FeedLink(atom.AtomBase):
  808.   """The gd:feedLink element"""
  809.  
  810.   _tag = 'feedLink'
  811.   _namespace = GDATA_NAMESPACE
  812.   _children = atom.AtomBase._children.copy()
  813.   _attributes = atom.AtomBase._attributes.copy()
  814.   _children['{%s}feed' % atom.ATOM_NAMESPACE] = ('feed', GDataFeed)
  815.   _attributes['rel'] = 'rel'
  816.   _attributes['readOnly'] = 'read_only'
  817.   _attributes['countHint'] = 'count_hint'
  818.   _attributes['href'] = 'href'
  819.  
  820.   def __init__(self, count_hint=None, href=None, read_only=None, rel=None,
  821.       feed=None, extension_elements=None, extension_attributes=None,
  822.       text=None):
  823.     self.count_hint = count_hint 
  824.     self.href = href
  825.     self.read_only = read_only
  826.     self.rel = rel
  827.     self.feed = feed
  828.     self.text = text
  829.     self.extension_elements = extension_elements or []
  830.     self.extension_attributes = extension_attributes or {}
  831.  
  832.  
  833. def FeedLinkFromString(xml_string):
  834.   return atom.CreateClassFromXMLString(EntryLink, xml_string)
  835.